package cn.hinglo.ehcahe.plugin;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.ehcache.CacheName;

/**
 * @createTime: 2019/1/29 0029
 * @author: HingLo
 * @description: 清除缓存拦截器，可以用在任何的方法上
 */
public class ClearCacheInterceptor implements Interceptor {

    @Override
    final public void intercept(Invocation inv) {
        inv.invoke();

        CacheKit.removeAll(buildCacheName(inv));
    }

    private String buildCacheName(Invocation inv) {
        CacheName cacheName = inv.getMethod().getAnnotation(CacheName.class);
        if (cacheName != null) {
            return cacheName.value();
        }
        cacheName = inv.getController().getClass().getAnnotation(CacheName.class);
        if (cacheName == null) {
            throw new RuntimeException("EvictInterceptor need CacheName annotation in controller.");
        }
        return cacheName.value();
    }
}